//Check to see if jQuery is loaded

	if (typeof(jQuery)=="undefined") {
		console.log("jQuery is not defined");
		initLoader();
	} else {
		jQuery(document).ready(function() {
			initGadget();
		});
	
	}
	
	function initLoader() {
		try {
			googleNowLoaded();		
		}
		catch(er){
			var gaJsHost = (("https:" == document.location.protocol) ? "https://www." : "http://www.");
			document.write(unescape("%3Cscript src='" + gaJsHost + "google.com/jsapi?callback=googleNowLoaded' type='text/javascript'%3E%3C/script%3E"));
			return true;
		}
	}
	
	function setGadgetStyles($opts) {
		$("#main-wrapper").css("background-color",$opts.backgroundColor);
		
	}
	
	
	function googleNowLoaded() {
	    google.load("jquery", "1.3.2"); //, {"callback":jqueryNowLoaded});

	    google.setOnLoadCallback(function(){
		    initGadget();
		});
	}
	
	function initGadget() {
		var twitter = new twitterHub("twitterGrid");
		
		var prefs = new gadgets.Prefs();
		var needle = prefs.getString("searchString");
		
		var backgroundColor = (prefs.getString('backgroundColor').match(/^#{1}[0-9abcdef]{6}$/i))?prefs.getString('backgroundColor'):"#000000";
		
		var opts = {
			needle:	prefs.getString("searchString").replace(/&#34;/gi, '"'),
			removeKeyword: prefs.getBool("removeKeyword"),
			autoRefresh: prefs.getBool("autoRefresh"),
			maxTweets: prefs.getInt("maxTweets"),
			backgroundColor: backgroundColor			
		};
		
		setGadgetStyles(opts);
		
		twitter.setNeedle(prefs.getString("searchString").replace(/&#34;/gi, ''));
		twitter.init(opts);
	}




function twitterHub(targetDiv) {
	this.targetDiv = targetDiv;
	console.log("you have initialized the twitterhub");
}

twitterHub.prototype.setNeedle = function(newNeedle) {
	//this.settings.needle = newNeedle;
	this.settings.needleRegExp = new RegExp(newNeedle,"gi");	
}

twitterHub.prototype.settings = {
	needle:"",
	needleRegExp:"",
	maxTweets:4,
	queryOptions:"",
	maxLibraryItems:"80"
}

twitterHub.prototype.init = function(opts) {
	
	this.settings = $.extend({},this.settings, opts);
	console.dir(this.settings);
	
	//Controller
	if (typeof(twitterHubController)!="object") {
		var twitterHubController = {
			timeout:"",
			targetDiv:this.targetDiv,
			settings:this.settings,
			init:function() {
				twitterHubDB.loadTweets();
				//put actions on buttons
				
			   $("#tweetsHub-button-refresh")
					.css({cursor:"pointer"})
					.unbind()
					.data("needle",twitterHubController.settings.needle)
					.one("customReload", function() {
						var needle = $(this).data("needle");
						//needleTracer = needle;
						twitterHubController.init();
					})
					.one("click", function() {
						$(this).trigger("customReload")
						clearTimeout(twitterHubController.timeout);
					});
				
				if(twitterHubDB.library.length>this.settings.maxLibraryItems) {
					this.cleanList(this.settings.maxLibraryItems);
				}
				
				if (twitterHubController.settings.autoRefresh) {
					twitterHubController.timeout = setTimeout(function(){$("#tweetsHub-button-refresh").trigger("customReload")},60000);
				}
			},
			cleanList:function(maxcount) {
				twitterHubDB.cleanList(maxcount);
				
			}
		}
	}
	
	//View 
	if (typeof(twitterHubView)!="object") {
		var twitterHubView = {
			latestView:function() {
				$("#"+twitterHubController.targetDiv).html("").hide();
				
				for (var i=0; i < twitterHubDB.library.length; i++) {
					
					//Set up each of the values
					var tweet = twitterHubDB.library[i].text.replace(twitterHubController.settings.needleRegExp, "").replace(/^\s*/, "").replace(/\s*$/, "");
					var tweeter = twitterHubDB.library[i].from_user;
					var twitTime = relative_time(twitterHubDB.library[i].created_at);
					var main = (i==0)?"Latest":"Default";
					var main2 = (i==0)?"font-size:13pt; margin-bottom:6px;":"margin-bottom:6px;";
					
					//Append values and formatting to target div
					$("#"+twitterHubController.targetDiv).append('<div class="tweet">'+
																 '<div class="tweet'+main+'" style="'+main2+'">'+tweet+'</div>'+
																 '<div style="font-size:7pt;"><span class="twitterUser">'+tweeter+'</span><span class="twitterTime"> - '+twitTime+'</span></div>'+
																 '</div>');
					
					//Check to see if we overflowed
					var tooTall = $("#"+twitterHubController.targetDiv).height();
					var tallLimit = 290-(((i+1)*6)+(i*12));
					if(parseInt(tooTall) > tallLimit) {
						$(".tweet:last").remove();
						$("#"+twitterHubController.targetDiv).fadeIn();
						break;
					}
					
				}				
			},
			runningView:function() {
				$("#"+twitterHubController.targetDiv).html("").hide();
				
				for (var i=0; i < twitterHubDB.library.length; i++) {
					
					//Set up each of the values
					var tweet = twitterHubDB.library[i].text;
					if (twitterHubController.settings.removeKeyword) {
						tweet = tweet.replace(twitterHubController.settings.needleRegExp, "");
					} else {
						tweet = tweet.replace(twitterHubController.settings.needleRegExp, "<strong>"+twitterHubController.settings.needle.replace(/"*/gi, "")+"</strong>");
					}
					tweet = tweet.replace(/^\s*/, "").replace(/\s*$/, "");
					
					var tweeter = twitterHubDB.library[i].from_user;
					var twitTime = relative_time(twitterHubDB.library[i].created_at);
					var main = (i==0)?"Latest":"Default";
					var main2 = (i==0)?"font-size:13pt; margin-bottom:6px;":"margin-bottom:6px;";
					
					//Append values and formatting to target div
					$("#"+twitterHubController.targetDiv).append('<div class="tweet">'+
																 '<div class="tweet'+main+'" style="'+main2+'">'+tweet+'</div>'+
																 '<div style="font-size:7pt;"><span class="twitterUser">'+tweeter+'</span><span class="twitterTime"> - '+twitTime+'</span></div>'+
																 '</div>');
					
				}
				
				$("#"+twitterHubController.targetDiv).show();
			}
		}
	}
	
	//Model
	if (typeof(twitterHubDB)!="object") {
		var twitterHubDB = {
			library:new Array(),
			lastRefresh:"",
			loadTweets:function() {
				$.ajax({
					type:"GET",
					url:"http://search.twitter.com/search.json",
					dataType:"jsonp",
					data:"q="+escape(twitterHubController.settings.needle)+twitterHubController.settings.queryOptions+"&since_id="+this.lastRefresh,
					error: function(XMLHttpRequest, textStatus, errorThrown){
						$('<p></p>')
						.html("There was an error with your request")
						.appendTo('body');
						returnVal = false;
					},
					//jsonp: "",
					success: function(html) {
						var twitterQueryData = eval(html);
						if (twitterQueryData.results.length >0) {
							twitterHubDB.lastRefresh = twitterQueryData.max_id;
							
							for (var i=twitterQueryData.results.length-1; i>=0; i--) {
								ARArrayTracer = twitterHubDB.library.unshift(twitterQueryData.results[i]);	
								
							}
						}
						
					},
					complete: function() {
						twitterHubView.runningView();	
					}
				});	
				
			},
			cleanList:function(maxcount) {
				var howmany = (this.library.length-maxcount);
				//console.log("running clean list. howmany:"+howmany+" maxcount:"+maxcount);
				this.library.splice(maxcount,howmany);
				
			}
			
		}
	}
	
	twitterHubController.init();
	
}

function relative_time(C){	
	var A=Date.parse(C);
	var D=new Date();
	var E=parseInt((D.getTime()-A)/1000);
	E=E+(D.getTimezoneOffset())-420;
	if(E<60)
		{ return "less than a minute ago" }
	else
		{ if (E<120) 
			{ return "about a minute ago" }
		else
			{
				if (E<(60*60)) {
					return (parseInt(E/60)).toString()+" minutes ago"}
				else {
					if(E<(120*60)) {
						return "about an hour ago"
					}
					else {
						if(E<(24*60*60)) {
							return "about "+(parseInt(E/3600)).toString()+" hours ago"
						}
						else {
							if(E<(48*60*60))
								{return"1 day ago"}
							else{return(parseInt(E/86400)).toString()+" days ago"}
						}
					}
				}
			}
		}
}